// 注入脚本 - 在页面主世界中运行，重写存储和Cookie API
(function() {
  'use strict';
  
  console.log('SessionBox: 注入脚本开始执行');
  
  // 立即检查并阻止原生localStorage访问
  const originalLocalStorageValue = window.localStorage;
  console.log('SessionBox: 原生localStorage状态:', originalLocalStorageValue);
  
  // 会话存储数据
  const sessionStorageData = {
    localStorage: {},
    sessionStorage: {},
    cookies: {}
  };
  
  let currentSessionId = 'unknown';
  let sessionConfig = null;
  let sessionInitialized = false;
  
  // 与内容脚本通信
  function sendMessageToContentScript(message) {
    window.postMessage({
      type: 'SESSIONBOX_FROM_INJECTED',
      ...message
    }, '*');
  }
  
  // 监听来自内容脚本的消息
  window.addEventListener('message', (event) => {
    if (event.source !== window) return;
    
    if (event.data.type === 'SESSIONBOX_TO_INJECTED') {
      const { action, data } = event.data;
      
      switch (action) {
        case 'INIT_SESSION':
          currentSessionId = data.sessionId || 'unknown';
          sessionConfig = data.sessionConfig;
          
          // 加载会话数据
          if (data.storageData) {
            sessionStorageData.localStorage = data.storageData.localStorage || {};
            sessionStorageData.sessionStorage = data.storageData.sessionStorage || {};
          } else {
            sessionStorageData.localStorage = {};
            sessionStorageData.sessionStorage = {};
          }
          
          if (data.cookieData) {
            sessionStorageData.cookies = data.cookieData;
          } else {
            sessionStorageData.cookies = {};
          }
          
          sessionInitialized = true;
          
          console.log('SessionBox: 会话初始化完成，ID:', currentSessionId);
          console.log('SessionBox: 存储数据:', sessionStorageData);
          console.log('SessionBox: 会话初始化状态:', sessionInitialized);
          
          // 会话初始化完成后，立即保存当前内存中的数据
          if (Object.keys(sessionStorageData.localStorage).length > 0) {
            console.log('SessionBox: 保存内存中的localStorage数据');
            sendMessageToContentScript({
              action: 'SAVE_STORAGE',
              type: 'localStorage',
              data: sessionStorageData.localStorage
            });
          }
          
          if (Object.keys(sessionStorageData.sessionStorage).length > 0) {
            console.log('SessionBox: 保存内存中的sessionStorage数据');
            sendMessageToContentScript({
              action: 'SAVE_STORAGE',
              type: 'sessionStorage',
              data: sessionStorageData.sessionStorage
            });
          }
          
          if (Object.keys(sessionStorageData.cookies).length > 0) {
            console.log('SessionBox: 保存内存中的Cookie数据');
            sendMessageToContentScript({
              action: 'SAVE_COOKIES',
              cookies: sessionStorageData.cookies
            });
          }
          
          break;
      }
    }
  });
  
  // 保存原始API
  const originalLocalStorage = window.localStorage;
  const originalSessionStorage = window.sessionStorage;
  const originalCookieDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
  
  // 创建会话localStorage
  const sessionLocalStorage = {
    getItem: function(key) {
      // 即使会话未初始化，也先从内存中读取数据
      const value = sessionStorageData.localStorage[key];
      const result = value !== undefined ? value : null;
      
      if (!sessionInitialized) {
        console.log(`SessionBox: [会话${currentSessionId}] localStorage.getItem("${key}") -> ${result} (会话未初始化，从内存读取)`);
      } else {
        console.log(`SessionBox: [会话${currentSessionId}] localStorage.getItem("${key}") -> ${result}`);
      }
      
      return result;
    },
    
    setItem: function(key, value) {
      console.log(`SessionBox: [会话${currentSessionId}] localStorage.setItem("${key}", "${value}")`);
      sessionStorageData.localStorage[key] = String(value);
      
      // 只有在会话已初始化时才通知内容脚本保存数据
      if (sessionInitialized) {
        sendMessageToContentScript({
          action: 'SAVE_STORAGE',
          type: 'localStorage',
          data: sessionStorageData.localStorage
        });
      } else {
        console.log('SessionBox: 会话未初始化，数据暂存在内存中');
      }
    },
    
    removeItem: function(key) {
      console.log(`SessionBox: localStorage.removeItem("${key}")`);
      delete sessionStorageData.localStorage[key];
      
      // 只有在会话已初始化时才通知内容脚本保存数据
      if (sessionInitialized) {
        sendMessageToContentScript({
          action: 'SAVE_STORAGE',
          type: 'localStorage',
          data: sessionStorageData.localStorage
        });
      } else {
        console.log('SessionBox: 会话未初始化，删除操作暂存在内存中');
      }
    },
    
    clear: function() {
      console.log('SessionBox: localStorage.clear()');
      sessionStorageData.localStorage = {};
      
      // 只有在会话已初始化时才通知内容脚本保存数据
      if (sessionInitialized) {
        sendMessageToContentScript({
          action: 'SAVE_STORAGE',
          type: 'localStorage',
          data: sessionStorageData.localStorage
        });
      } else {
        console.log('SessionBox: 会话未初始化，清除操作暂存在内存中');
      }
    },
    
    key: function(index) {
      const keys = Object.keys(sessionStorageData.localStorage);
      const key = keys[index] || null;
      console.log(`SessionBox: localStorage.key(${index}) ->`, key);
      return key;
    },
    
    get length() {
      const length = Object.keys(sessionStorageData.localStorage).length;
      console.log('SessionBox: localStorage.length ->', length);
      return length;
    }
  };
  
  // 创建会话sessionStorage
  const sessionSessionStorage = {
    getItem: function(key) {
      const value = sessionStorageData.sessionStorage[key];
      const result = value !== undefined ? value : null;
      
      if (!sessionInitialized) {
        console.log(`SessionBox: sessionStorage.getItem("${key}") -> ${result} (会话未初始化，从内存读取)`);
      } else {
        console.log(`SessionBox: sessionStorage.getItem("${key}") -> ${result}`);
      }
      
      return result;
    },
    
    setItem: function(key, value) {
      console.log(`SessionBox: sessionStorage.setItem("${key}", "${value}")`);
      sessionStorageData.sessionStorage[key] = String(value);
      
      // 只有在会话已初始化时才通知内容脚本保存数据
      if (sessionInitialized) {
        sendMessageToContentScript({
          action: 'SAVE_STORAGE',
          type: 'sessionStorage',
          data: sessionStorageData.sessionStorage
        });
      } else {
        console.log('SessionBox: 会话未初始化，sessionStorage数据暂存在内存中');
      }
    },
    
    removeItem: function(key) {
      console.log(`SessionBox: sessionStorage.removeItem("${key}")`);
      delete sessionStorageData.sessionStorage[key];
      
      // 只有在会话已初始化时才通知内容脚本保存数据
      if (sessionInitialized) {
        sendMessageToContentScript({
          action: 'SAVE_STORAGE',
          type: 'sessionStorage',
          data: sessionStorageData.sessionStorage
        });
      } else {
        console.log('SessionBox: 会话未初始化，sessionStorage删除操作暂存在内存中');
      }
    },
    
    clear: function() {
      console.log('SessionBox: sessionStorage.clear()');
      sessionStorageData.sessionStorage = {};
      
      // 只有在会话已初始化时才通知内容脚本保存数据
      if (sessionInitialized) {
        sendMessageToContentScript({
          action: 'SAVE_STORAGE',
          type: 'sessionStorage',
          data: sessionStorageData.sessionStorage
        });
      } else {
        console.log('SessionBox: 会话未初始化，sessionStorage清除操作暂存在内存中');
      }
    },
    
    key: function(index) {
      const keys = Object.keys(sessionStorageData.sessionStorage);
      const key = keys[index] || null;
      console.log(`SessionBox: sessionStorage.key(${index}) ->`, key);
      return key;
    },
    
    get length() {
      const length = Object.keys(sessionStorageData.sessionStorage).length;
      console.log('SessionBox: sessionStorage.length ->', length);
      return length;
    }
  };
  
  // 重写localStorage
  Object.defineProperty(window, 'localStorage', {
    get: () => sessionLocalStorage,
    set: () => {}, // 阻止重新赋值
    configurable: false,
    enumerable: true
  });
  
  // 重写sessionStorage
  Object.defineProperty(window, 'sessionStorage', {
    get: () => sessionSessionStorage,
    set: () => {}, // 阻止重新赋值
    configurable: false,
    enumerable: true
  });
  
  // 重写document.cookie
  Object.defineProperty(document, 'cookie', {
    get: function() {
      const cookieStrings = [];
      for (const [name, value] of Object.entries(sessionStorageData.cookies)) {
        cookieStrings.push(`${name}=${value}`);
      }
      const cookies = cookieStrings.join('; ');
      console.log('SessionBox: document.cookie 被读取 ->', cookies);
      return cookies;
    },
    
    set: function(value) {
      console.log('SessionBox: document.cookie 被设置 ->', value);
      
      // 解析Cookie字符串
      const parts = value.split(';');
      const mainPart = parts[0].trim();
      const [name, cookieValue] = mainPart.split('=');
      
      if (name && cookieValue !== undefined) {
        sessionStorageData.cookies[name.trim()] = cookieValue.trim();
        console.log('SessionBox: Cookie已保存到会话:', name, '=', cookieValue);
        
        // 只有在会话已初始化时才通知内容脚本保存Cookie
        if (sessionInitialized) {
          sendMessageToContentScript({
            action: 'SAVE_COOKIES',
            cookies: sessionStorageData.cookies
          });
        } else {
          console.log('SessionBox: 会话未初始化，Cookie数据暂存在内存中');
        }
      }
    },
    
    configurable: false,
    enumerable: true
  });
  
  console.log('SessionBox: 注入脚本初始化完成');
  
  // 通知内容脚本注入脚本已准备好
  sendMessageToContentScript({
    action: 'INJECTED_READY'
  });
  
})(); 